import java.io.File;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Collection;
import java.util.HashSet;

import org.apache.commons.io.DirectoryWalker;

import org.albert.toolkit.FileSystem;

/**
 * Makes an EXT directory compatible to be copied into to an NTFS file system.
 * 
 * @author Albert Walner
 * @version 1.2
 * 
 */
public class Compatibilator extends DirectoryWalker<File> {

	private String path;
	private String errorMessage = "Error!";
	private ProtocolTable protocolTable;

	/*
	 * This array of array will be build up while walking through the
	 * directory.<br /> The first array determines the depth where the
	 * file/directory is located.<br /> So that it can be added into the
	 * HashSet.
	 */
	private ArrayList<HashSet<File>> files = new ArrayList<HashSet<File>>();

	public Compatibilator(ProtocolTable protocolTable) {
		this.protocolTable = protocolTable;
	}

	@Override
	protected void handleFile(File file, int depth, Collection<File> results) {
		addIntoSet(file, depth);
		// translateFromExtToNtfs(file);
	}

	@Override
	protected boolean handleDirectory(File file, int depth,
			Collection<File> result) {
		addIntoSet(file, depth);
		// translateFromExtToNtfs(file);
		return true;
	}

	private void addIntoSet(File file, int depth) {
		HashSet<File> correctSet;
		if ((depth < files.size()) && (files.get(depth) != null)) {
			correctSet = files.get(depth);
		} else {
			correctSet = new HashSet<File>();
			files.ensureCapacity(depth);
			files.add(depth, correctSet);
		}
		correctSet.add(file);
	}

	private void translateFromExtToNtfs(File file) {

		File correctedFile = FileSystem.correctFileDirName(file);

		if (!file.equals(correctedFile)) {
			protocolTable.addProtocoll(file.getAbsolutePath(),
					correctedFile.getAbsolutePath());
			file.renameTo(correctedFile);
		}
	}

	public String getErrorMessage() {
		return errorMessage;
	}

	public boolean run(String currentPath) {
		path = currentPath;
		if (path == null) {
			errorMessage = "Provide a source directory first!";
			return false;
		} else {
			try {
				walk(new File(path), null);

				// correct everything
				for (int i = files.size() - 1; i > 0; i--) {
					HashSet<File> set = files.get(i);
					for (File file : set) {
						translateFromExtToNtfs(file);
					}
				}
			} catch (IOException e) {
				errorMessage = e.getMessage();
				return false;
			}
			return true;
		}
	}
}
